package com.yvan.leto;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.util.StatusPrinter;
import com.google.common.base.Strings;
import com.yvan.leto.ConfigChangeEvent;
import com.yvan.leto.ConfigListener;
import com.yvan.leto.LetoManage;
import com.yvan.leto.SegmentHelper;
import lombok.Cleanup;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;

@Slf4j
public class LogbackListener implements ConfigListener {

    private String logbackConfigContent;

    @Override
    public String watchSegment() {
        return SegmentHelper.LOGBACK;
    }

    @Override
    @SneakyThrows
    public void onChange(ConfigChangeEvent changeEvent) {
        final String xmlContent = changeEvent.getChanges();
        if (Strings.isNullOrEmpty(xmlContent)) {
            log.info("logback configuration empty!");
            return;
        }

        @Cleanup ByteArrayInputStream inputStream = new ByteArrayInputStream(xmlContent.getBytes("utf-8"));
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(lc);
        lc.reset();
        configurator.doConfigure(inputStream);
        StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
        log.info("logback configuration has inited!");

        logbackConfigContent = xmlContent;
    }

    @Override
    public void setup(LetoManage letoManage) {

    }

    public String getLogbackConfigContent() {
        return logbackConfigContent;
    }
}

